#include <stdio.h>
#include <libusb-1.0/libusb.h>

int main() {
    libusb_device **devs;          // 设备列表
    libusb_context *ctx = NULL;    // libusb 上下文
    int r;                         // 返回值
    ssize_t cnt;                   // 设备数量

    // 初始化 libusb
    r = libusb_init(&ctx);
    if (r < 0) {
        fprintf(stderr, "初始化 libusb 失败: %s\n", libusb_error_name(r));
        return 1;
    }

    // 获取设备列表
    cnt = libusb_get_device_list(ctx, &devs);
    if (cnt < 0) {
        fprintf(stderr, "获取设备列表失败: %s\n", libusb_error_name((int)cnt));
        libusb_exit(ctx);
        return 1;
    }

    printf("找到 %zd 个 USB 设备:\n", cnt);
    printf("=========================================\n");

    // 遍历设备列表
    for (ssize_t i = 0; i < cnt; i++) {
        libusb_device *dev = devs[i];
        struct libusb_device_descriptor desc;
        libusb_device_handle *handle = NULL;
        char manufacturer[256] = "未知", product[256] = "未知";

        // 获取设备描述符
        r = libusb_get_device_descriptor(dev, &desc);
        if (r < 0) {
            fprintf(stderr, "获取设备描述符失败: %s\n", libusb_error_name(r));
            continue;
        }

        // 尝试打开设备以获取详细信息
        r = libusb_open(dev, &handle);
        if (r == LIBUSB_SUCCESS) {
            // 获取制造商字符串
            if (desc.iManufacturer > 0) {
                libusb_get_string_descriptor_ascii(handle, desc.iManufacturer,
                    (unsigned char*)manufacturer, sizeof(manufacturer));
            }
            // 获取产品字符串
            if (desc.iProduct > 0) {
                libusb_get_string_descriptor_ascii(handle, desc.iProduct,
                    (unsigned char*)product, sizeof(product));
            }
            libusb_close(handle);
        }

        // 打印设备信息
        printf("设备 %ld:\n", i + 1);
        printf("  Vendor ID:  0x%04x\n", desc.idVendor);
        printf("  Product ID: 0x%04x\n", desc.idProduct);
        printf("  制造商:     %s\n", manufacturer);
        printf("  产品名:     %s\n", product);
        printf("  USB 版本:   %d.%d\n", desc.bcdUSB >> 8, desc.bcdUSB & 0xFF);
        printf("  USB 类:     %d\n", desc.bDeviceClass);
        printf("-----------------------------------------\n");
    }

    // 释放设备列表并退出 libusb
    libusb_free_device_list(devs, 1);
    libusb_exit(ctx);
    return 0;
}

